<?php
use \think\paginator\driver\Bootstrap;

class MyPaginator extends Bootstrap{
    private $ajax_callback_fnc = 'ajax_callback_fnc';

    private $is_ajax = false;

    public function __construct($items, int $listRows, int $currentPage = 1, int $total = null, bool $simple = false, array $options = [])
    {
        //是否是ajax请求
        $this->is_ajax = request()->isAjax();
        if(input('?ajax_callback_fnc')){
            $this->ajax_callback_fnc = input('ajax_callback_fnc','','trim');
        }
        $options = array_merge($options,['query'=>request()->param()]);
        parent::__construct($items,$listRows,$currentPage,$total,$simple,$options);
    }


    /**
     * 渲染分页html
     * @return mixed
     */
    public function render()
    {
        if ($this->hasPages()) {
            return sprintf(
                '<div class="pages wow fadeInUp" id="my-paginator">%s %s %s</div>',
                $this->getPreviousButton("上一页"),
                $this->getLinks(),
                $this->getNextButton("下一页")
            );
        }
    }


    /**
     * 生成一个可点击的按钮
     *
     * @param  string $url
     * @param  string $page
     * @return string
     */
    protected function getAvailablePageWrapper(string $url, string $page): string
    {
        $href = htmlentities($url);
        if($this->is_ajax){
            $ajax_page = $page;
            if(!is_numeric($page)){
                if($page=="上一页"){
                    $ajax_page = $this->currentPage-1;
                }else{
                    $ajax_page = $this->currentPage+1;
                }
            }
            $href = 'javascript:'.$this->ajax_callback_fnc.'('.$ajax_page.');';
        }
        return '<a href="' . $href . '" class="prev">'.$page.'</a>';
    }

    /**
     * 生成一个禁用的按钮
     *
     * @param  string $text
     * @return string
     */
    protected function getDisabledTextWrapper(string $text): string
    {
        return '<a class="prev disabled">'.$text.'</a>';
    }

    /**
     * 生成一个激活的按钮
     *
     * @param  string $text
     * @return string
     */
    protected function getActivePageWrapper(string $text): string
    {
        return '<span><a class="cur">'.$text.'</a></span>';
    }

}